import router from '@/router'
import {post} from '@/util/request'
import {getAddress} from '@/plugin/Map/Mapaddress'

export default {
	namespace:'organization',
	namespaced:true,
	state:{
		isLoading:false,
		isModalLoading:true,
		isSubmiting:false,
		orgList: [],
		orgDetail:{}
	},
	mutations:{
		changeLoading(state,v){
			state.isLoading = v;
		},
		changeModalLoading(state,v){
			state.isModalLoading = v;
		},
		changeOrglist(state,v){
			state.orgList = v;
		},
		changeOrgdetail(state,v) {
			state.orgDetail = v;
		},
		changeSubmit(state,v){
			state.isSubmiting = v;
		}
	},
	actions:{
		async reload({commit}){
			commit('changeLoading',true);
			let res = await post('/base/org/findOrgs');
			commit('changeOrglist',res.data.data);
			commit('changeLoading',false);
		},
		async loadOrg({commit}, id){
			commit('changeModalLoading',true);
			let res = await post('/base/org/view', {orgId:id});
			let org = res.data.data;
      let adds = await getAddress([[org.lng,org.lat]]);
      org.address = adds.length > 0 ? adds[0].formattedAddress : '';
			commit('changeOrgdetail',res.data.data);
			commit('changeModalLoading',false);
		},
		getAddress({commit},[lng,lat]){
			return getAddress([[lng,lat]]).then(res => {
				return res;
			});
		},
		getParentTree({commit},pid){
			commit('changeModalLoading',true);
			return post('/base/org/view', {orgId:pid}).then(json => {
				commit('changeModalLoading',false);
				return json.data.data.resourceVo;
			});
		},
		disableOrg({commit}, orgId) {
			return post('/base/org/forbidOrg',{orgId}).then(res => {
				return res.data;
			});
		},
		addOrg({commit}, form){
			commit('changeSubmit',true);
			return post('/base/org/doAdd', form).then(res => {
				commit('changeSubmit',false);
				return res.data;
			});
		},
		editOrg({commit}, form){
			let data = {...form};
			delete data.addTime; // 把这个字段删除
			commit('changeSubmit',true);
			return post('/base/org/doUpdate', data).then(res => {
				commit('changeSubmit',false);
				return res.data;
			});
		},
		resetPassword({commit},data){
			return post('/auth/employee/resetPassword',data).then(res => {
				return res.data;
			});
		}
	},
	subscriptions({dispatch},router){
		//给路由加监听一旦进入module绑定的页面时dispatch初始化action
		router.afterEach((to,from)=>{
			if(to.name === this.namespace){
				dispatch('reload',{})
			}
		})
	}
}
